package com.aiyige.page.publish.majorcourse;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.service.ApiService;
import com.aiyige.base.eventbus.EventCopyMajorCourseFinish;
import com.aiyige.base.eventbus.EventEditMajorCourseFinish;
import com.aiyige.location.LocationService;
import com.aiyige.location.model.LocationData;
import com.aiyige.model.Divide;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.interest.selectpublishinterest.SelectPublishInterestPage;
import com.aiyige.page.interest.util.InterestUtil;
import com.aiyige.page.publish.CommonTipDialog;
import com.aiyige.page.publish.adapter.FormTraingCardAdapter;
import com.aiyige.page.publish.coursedescription.CourseDescriptionPage;
import com.aiyige.page.publish.coursedescription.model.CourseCover;
import com.aiyige.page.publish.courseschedule.CourseSchedulePage;
import com.aiyige.page.publish.courseschedule.model.CourseScheduleModel;
import com.aiyige.page.publish.editbanner.EditBannerPage;
import com.aiyige.page.publish.guarantee.GuaranteePage;
import com.aiyige.page.publish.guarantee.model.GuaranteeItem;
import com.aiyige.page.publish.guarantee.util.GuaranteeUtil;
import com.aiyige.page.publish.majorcourse.model.ClassLocation;
import com.aiyige.page.publish.majorcourse.model.MajorCourseFormModel;
import com.aiyige.page.publish.majorcourse.model.MajorCourseType;
import com.aiyige.page.publish.selectlocation.SelectLocationPage;
import com.aiyige.page.publish.selectlocation.model.SelectLocationData;
import com.aiyige.page.publish.selecttraingcard.SelectTraingCardPage;
import com.aiyige.page.publish.selecttraingcard.model.TraingCard;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.CancelEditDialogUtil;
import com.aiyige.utils.ColorUtil;
import com.aiyige.utils.DateFormatUtil;
import com.aiyige.utils.DivideUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.EditTextAutoMoveCursorToEndFocusChangeListener;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ExcludeEmojiInputFilter;
import com.aiyige.utils.ExcludeSpaceInputFilter;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.exception.FormFieldException;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.ShSwitchView;
import com.aiyige.utils.widget.articleview.model.ArticleNode;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.netease.nim.uikit.common.activity.UI;
import com.netease.nim.uikit.common.util.string.StringUtil;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.PublishMajorCourseFormPage, extras = ARouterConfig.EXTRA_NEED_LOGIN | ARouterConfig.EXTRA_NEED_BINDPHONE)
public class PublishMajorCourseFormPage extends BaseActivity {
    public static final int REQUEST_CODE_SELECT_INTEREST = 1;
    public static final int REQUEST_CODE_SELECT_TRAING_CARD = 6;
    public static final int REQUEST_CODE_SELECT_CLASS_LOCATION = 7;
    public static final int REQUEST_CODE_INPUT_COURSE_SCHEDULE = 8;
    public static final int REQUEST_CODE_NEXT = 9;
    public static final int REQUEST_CODE_SELECT_GUARANTEE = 11;
    public static final int REQUEST_CODE_EDIT_BANNER = 12;
    @Autowired
    MajorCourseFormModel formModel = null;

    CommonBottomDialogFragment openClassConditionDialog;
    FormTraingCardAdapter formTraingCardAdapter;
    @BindView(R.id.containerLayout)
    View containerLayout;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleEt)
    EditText titleEt;
    @BindView(R.id.formTitleLayout)
    ViewGroup formTitleLayout;
    @BindView(R.id.interestTv)
    TextView interestTv;
    @BindView(R.id.interestLayout)
    RelativeLayout interestLayout;
    @BindView(R.id.openBuyLayout)
    RelativeLayout openBuyLayout;
    @BindView(R.id.classSizeEt)
    EditText classSizeEt;
    @BindView(R.id.classSizeLayout)
    RelativeLayout classSizeLayout;
    @BindView(R.id.openClassConditionTv)
    TextView openClassConditionTv;
    @BindView(R.id.openClassConditionLayout)
    RelativeLayout openClassConditionLayout;
    @BindView(R.id.startClassDateTv)
    TextView startClassDateTv;
    @BindView(R.id.startClassDateLayout)
    RelativeLayout startClassDateLayout;
    @BindView(R.id.endClassDateTv)
    TextView endClassDateTv;
    @BindView(R.id.endClassDateLayout)
    RelativeLayout endClassDateLayout;
    @BindView(R.id.minClassSizeEt)
    EditText minClassSizeEt;
    @BindView(R.id.minClassSizeLayout)
    RelativeLayout minClassSizeLayout;
    @BindView(R.id.confirmDateTv)
    TextView confirmDateTv;
    @BindView(R.id.confirmDateLayout)
    RelativeLayout confirmDateLayout;
    @BindView(R.id.minClassSizeContainer)
    ExpandableLayout minClassSizeContainer;
    @BindView(R.id.classLocationTv)
    TextView classLocationTv;
    @BindView(R.id.classLocationLayout)
    RelativeLayout classLocationLayout;
    @BindView(R.id.suitableLearnAgeLayout)
    RelativeLayout suitableLearnAgeLayout;
    @BindView(R.id.learnTargetLayout)
    RelativeLayout learnTargetLayout;
    @BindView(R.id.suitableLearnPeopleLayout)
    RelativeLayout suitableLearnPeopleLayout;
    @BindView(R.id.priceEt)
    EditText priceEt;
    @BindView(R.id.priceLayout)
    RelativeLayout priceLayout;
    @BindView(R.id.courseNumberEt)
    EditText courseNumberEt;
    @BindView(R.id.courseNumberLayout)
    RelativeLayout courseNumberLayout;
    @BindView(R.id.singleClassDurationEt)
    EditText singleClassDurationEt;
    @BindView(R.id.singleClassDurationLayout)
    RelativeLayout singleClassDurationLayout;
    @BindView(R.id.platformDividendEt)
    EditText platformDividendEt;
    @BindView(R.id.platformDividendLayout)
    RelativeLayout platformDividendLayout;
    @BindView(R.id.platformDividendDescContainer)
    ExpandableLayout platformDividendDescContainer;
    @BindView(R.id.traingCardTv)
    TextView traingCardTv;
    @BindView(R.id.traingCardRv)
    RecyclerView traingCardRv;
    @BindView(R.id.traingCardLayout)
    RelativeLayout traingCardLayout;
    @BindView(R.id.singleClassPriceEt)
    EditText singleClassPriceEt;
    @BindView(R.id.singleClassPriceLayout)
    RelativeLayout singleClassPriceLayout;
    @BindView(R.id.singleClassPriceContainer)
    ExpandableLayout singleClassPriceContainer;
    @BindView(R.id.nextBtn)
    TextView nextBtn;
    @BindView(R.id.openBuySwitch)
    ShSwitchView openBuySwitch;
    KeyboardUtil.KeyboardMonitor keyboardMonitor;

    List<MajorCourseType> majorCourseTypeList = null;
    @BindView(R.id.majorCourseTypeTv)
    TextView majorCourseTypeTv;
    @BindView(R.id.majorCourseTypeLayout)
    RelativeLayout majorCourseTypeLayout;
    @BindView(R.id.confirmDateTipIv)
    ImageView confirmDateTipIv;
    @BindView(R.id.courseScheduleLayout)
    RelativeLayout courseScheduleLayout;
    MajorCourseTypeDialog majorCourseTypeDialog;
    BroadcastReceiver receiver;
    boolean keyboardVisiable = false;
    @BindView(R.id.suitableLearnAgeEt)
    EditText suitableLearnAgeEt;
    @BindView(R.id.learnTargetEt)
    EditText learnTargetEt;
    @BindView(R.id.suitablePeopleEt)
    EditText suitablePeopleEt;
    @BindView(R.id.cspSwitch)
    ShSwitchView cspSwitch;
    Handler mainHandler;
    @BindView(R.id.courseScheduleTv)
    TextView courseScheduleTv;
    Divide divide = null;
    @BindView(R.id.guaranteeTv)
    TextView guaranteeTv;
    @BindView(R.id.courseCoverIv)
    ImageView courseCoverIv;
    @BindView(R.id.bannerLayout)
    RelativeLayout bannerLayout;
    @BindView(R.id.platformDividendExplainBtn)
    ImageView platformDividendExplainBtn;
    @BindView(R.id.cspExplainBtn)
    ImageView cspExplainBtn;
    @BindView(R.id.cspLayout)
    RelativeLayout cspLayout;
    @BindView(R.id.guaranteeExplainBtn)
    ImageView guaranteeExplainBtn;
    @BindView(R.id.guaranteeLayout)
    RelativeLayout guaranteeLayout;
    String dependOnPopulationNotify = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_publish_major_course_form);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (formModel == null) {
            finish();
            return;
        }
        mainHandler = new Handler(Looper.getMainLooper());
        switch (formModel.getOperationType()) {
            case PublishUtil.OPERATION_TYPE_EDIT:
                titleTv.setText(R.string.edit_major_course);
                break;
            default:
                titleTv.setText(R.string.publish_major_course);
                break;
        }
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    switch (intent.getAction()) {
                        case LocationService.ACTION_LOCATION_FINISH:
                            try {
                                LocationData locationData = intent.getParcelableExtra(LocationService.EXTRA_LOCATION_DATA);
                                if (locationData.isSuccess() && formModel.getClassLocation() == null) {
                                    formModel.setClassLocation(ClassLocation.newBuilder()
                                            .city(locationData.getCity())
                                            .province(locationData.getProvince())
                                            .id(DummyDataUtil.getCityId(locationData.getProvince(), locationData.getCity()))
                                            .build());
                                } else {
                                    throw new Exception(StringUtils.getString(R.string.location_failed));
                                }
                            } catch (Exception e) {
                                if (formModel.getClassLocation() == null) {
                                    formModel.setClassLocation(ClassLocation.newBuilder().build());
                                }
                            }
                            updateView();
                            break;
                    }
                } catch (Exception e) {

                }
            }
        };
        initView();
        updateView();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocationService.ACTION_LOCATION_FINISH);
        registerReceiver(receiver, intentFilter);
        LocationService.startLocation(this);
        new MaybeRequestDivide(this, formModel).execute();
        maybeFreezeForm();
    }


    void initView() {
        keyboardMonitor = KeyboardUtil.KeyboardMonitor.newBuilder()
                .container(containerLayout)
                .callback(new KeyboardUtil.KeyboardMonitor.Callback() {
                    @Override
                    public void onKeyboardShow() {
                        keyboardVisiable = true;
                    }

                    @Override
                    public void onKeyboardHide() {
                        keyboardVisiable = false;
                        containerLayout.requestFocus();
                    }
                })
                .build()
                .install();
        titleEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(30, false)});
        suitableLearnAgeEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(15, false)});
        suitablePeopleEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(15, false)});
        learnTargetEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(15, false)});
        traingCardRv.setLayoutManager(new GridLayoutManager(this, 3));
        formTraingCardAdapter = new FormTraingCardAdapter();
        formTraingCardAdapter.bindToRecyclerView(traingCardRv);
        formTraingCardAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.deleteBtn:
                        adapter.remove(position);
                        break;
                }
            }
        });

        titleEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setTitle(s.toString());
            }
        });

        suitableLearnAgeEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setSuitableLearnAge(s.toString());
            }
        });
        suitablePeopleEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setSuitablePeople(s.toString());
            }
        });
        learnTargetEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setLearnTarget(s.toString());
            }
        });
        titleEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        suitableLearnAgeEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        suitablePeopleEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        learnTargetEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        classSizeEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        int value;
                        try {
                            value = Integer.parseInt(classSizeEt.getText().toString());
                        } catch (Exception e) {
                            throw new FormFieldException(R.string.invalid_integer);
                        }

                        if (value <= 0) {
                            throw new FormFieldException(R.string.invalid_integer);
                        }
                        int minClassSizeValue = Integer.MIN_VALUE;
                        try {
                            minClassSizeValue = Integer.parseInt(formModel.getMinClassSize());
                        } catch (Exception e) {

                        }
                        if (value < minClassSizeValue) {
                            throw new FormFieldException(R.string.class_size_not_less_than_min_class_size);
                        }
                        formModel.setClassSize(String.valueOf(value));
                    } catch (Exception e) {
                        ToastX.show(e.getMessage());
                        formModel.setClassSize(null);
                    }
                    updateView();
                } else {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            classSizeEt.setSelection(classSizeEt.getText().length());
                        }
                    });
                }
            }
        });

        minClassSizeEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        int value;
                        try {
                            value = Integer.parseInt(minClassSizeEt.getText().toString());
                        } catch (Exception e) {
                            throw new FormFieldException(R.string.invalid_integer);
                        }
                        if (value <= 0) {
                            throw new FormFieldException(R.string.invalid_integer);
                        }
                        int classSizeValue = Integer.MAX_VALUE;
                        try {
                            classSizeValue = Integer.parseInt(formModel.getClassSize());
                        } catch (Exception e) {

                        }
                        if (value > classSizeValue) {
                            throw new FormFieldException(R.string.min_class_size_not_greater_than_class_size);
                        }
                        formModel.setMinClassSize(String.valueOf(value));
                    } catch (Exception e) {
                        ToastX.show(e.getMessage());
                        formModel.setMinClassSize(null);
                    }
                    updateView();
                } else {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            minClassSizeEt.setSelection(minClassSizeEt.getText().length());
                        }
                    });
                }
            }
        });

        priceEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        String valueStr = priceEt.getText().toString().trim();
                        double value = Double.parseDouble(valueStr);
                        if (value < 0) {
                            throw new Exception();
                        }
                        valueStr = StringUtils.priceFormatEscapeRedundantTailZero(value);
                        formModel.setPrice(valueStr);
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_price);
                        formModel.setPrice(null);
                    }
                    updateView();
                } else {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            priceEt.setSelection(priceEt.getText().length());
                        }
                    });

                }
            }
        });

        courseNumberEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        int value = Integer.parseInt(courseNumberEt.getText().toString());
                        if (value <= 0) {
                            throw new Exception();
                        }
                        formModel.setCourseNumber(String.valueOf(value));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_integer);
                        formModel.setCourseNumber(null);
                    }
                    updateView();
                } else {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            courseNumberEt.setSelection(courseNumberEt.getText().length());
                        }
                    });

                }
            }
        });

        singleClassDurationEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        int value = Integer.parseInt(singleClassDurationEt.getText().toString());
                        if (value <= 0) {
                            throw new Exception();
                        }
                        formModel.setSingleClassDuration(String.valueOf(value));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_integer);
                        formModel.setSingleClassDuration(null);
                    }
                    updateView();
                } else {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            singleClassDurationEt.setSelection(singleClassDurationEt.getText().length());
                        }
                    });

                }
            }
        });

        platformDividendEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (divide == null) {
                    platformDividendEt.setText(TextUtils.isEmpty(formModel.getPlatformDividend()) ? "" : formModel.getPlatformDividend());
                    return;
                }
                if (!hasFocus) {
                    try {
                        String valueStr = platformDividendEt.getText().toString().trim();
                        double dividend = Double.parseDouble(valueStr);
                        if (dividend / 100 < divide.getMin()) {
                            throw new Exception("");
                        }
                        if (dividend / 100 > divide.getMax()) {
                            throw new Exception("Max");
                        }
                        formModel.setPlatformDividend(StringUtils.platformDividendFormat(dividend));
                    } catch (Exception e) {
                        ToastX.show(StringUtils.getString(R.string.platform_dividend_range, StringUtils.platformDividendFormat(divide.getMin() * 100), StringUtils.platformDividendFormat(divide.getMax() * 100)));
                        if ((e != null && !TextUtils.isEmpty(e.getMessage())) && e.getMessage().equals("Max")) {
                            formModel.setPlatformDividend(StringUtils.platformDividendFormat(divide.getMax() * 100));
                        } else {
                            formModel.setPlatformDividend(StringUtils.platformDividendFormat(divide.getMin() * 100));
                        }


                    }
                    updateView();
                } else {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            platformDividendEt.setSelection(platformDividendEt.getText().length());
                        }
                    });
                }
            }
        });

        singleClassPriceEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        String valueStr = singleClassPriceEt.getText().toString().trim();
                        double value = Double.parseDouble(valueStr);
                        if (value < 0) {
                            throw new Exception();
                        }
                        formModel.setSinglePrice(StringUtils.priceFormatEscapeRedundantTailZero(value));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_price);
                        formModel.setSinglePrice(null);
                    }
                    updateView();
                } else {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            singleClassPriceEt.setSelection(singleClassDurationEt.getText().length());
                        }
                    });
                }
            }
        });
        openBuySwitch.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                formModel.setOpenBuy(isOn);
            }
        });
        cspSwitch.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                formModel.setJoinConsumptionSecurityPlan(isOn);
            }
        });

        openClassConditionDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.open_class_condition_dialog)
                .viewIdList(R.id.dependOnOpenDateBtn, R.id.dependOnPopulationBtn, R.id.cancelBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.dependOnOpenDateBtn:
                                formModel.setOpenClassCondition(MajorCourseFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_OPEN_DATE);
                                break;
                            case R.id.dependOnPopulationBtn:
                                formModel.setOpenClassCondition(MajorCourseFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_POPULATION);
                                new DependOnPopulationNotifyTask(PublishMajorCourseFormPage.this).execute();
                                break;
                        }
                        updateView();
                    }
                })
                .build();
        majorCourseTypeDialog = MajorCourseTypeDialog.newInstance();
        majorCourseTypeDialog.setListener(new MajorCourseTypeDialog.Listener() {
            @Override
            public void onClick(MajorCourseType type) {
                formModel.setMajorCourseType(type);
                updateView();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {

        }

        keyboardMonitor.uninstall();
        super.onDestroy();
    }

    public CourseCover getDefaultCourseCover() {
        List<CourseCover> courseCoverList = formModel.getCourseDescriptionModel().getCourseCoverList();
        if (ListUtil.isEmpty(courseCoverList)) {
            return null;
        }
        for (CourseCover courseCover : courseCoverList) {
            if (courseCover.getType() == CourseCover.TYPE_NORMAL
                    && courseCover.getMediaType() == CourseCover.MEDIA_TYPE_PHOTO
                    && courseCover.isDefaultCover()) {
                return courseCover;
            }
        }
        return null;
    }

    public void updateView() {
        titleEt.setText(formModel.getTitle());
        if (!ListUtil.isEmpty(formModel.getInterestList())) {
            interestTv.setText(InterestUtil.joinInterestListTitle("、", formModel.getInterestList()));
        } else {
            interestTv.setText("");
        }


        if (formModel.getCover() != null) {
            courseCoverIv.setVisibility(View.VISIBLE);
            GlideUtil.with(this)
                    .asGif()
                    .loadCover(formModel.getCover().getImageUrl())
                    .into(courseCoverIv);
        } else {
            courseCoverIv.setVisibility(View.INVISIBLE);
        }

        if (ListUtil.isEmpty(formModel.getCourseScheduleModel().getArticleNodeList())) {
            courseScheduleTv.setText("");
        } else {
            ArticleNode articleNode = ListUtil.getFirstItem(formModel.getCourseScheduleModel().getArticleNodeList());
            if (articleNode != null && articleNode.getType() == ArticleNode.NODE_TYPE_TEXT) {
                courseScheduleTv.setText(TextUtils.isEmpty(articleNode.getText()) ? " " : articleNode.getText());
            } else {
                courseScheduleTv.setText(" ");
            }
        }

        if (!TextUtils.isEmpty(formModel.getMajorCourseType().getId())) {
            majorCourseTypeTv.setText(formModel.getMajorCourseType().getTitle());
        } else {
            majorCourseTypeTv.setText("");
        }

        if (formModel.getOpenBuy() != null) {
            openBuySwitch.setOn(formModel.getOpenBuy());
        } else {
            openBuySwitch.setOn(false);
        }
        cspSwitch.setOn(formModel.isJoinConsumptionSecurityPlan());
        classSizeEt.setText(formModel.getClassSize());
        if (formModel.getOpenClassCondition() != null) {
            switch (formModel.getOpenClassCondition()) {
                case MajorCourseFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_OPEN_DATE:
                    openClassConditionTv.setText(R.string.open_class_depend_on_open_date);
                    minClassSizeContainer.collapse();
                    break;
                case MajorCourseFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_POPULATION:
                    openClassConditionTv.setText(R.string.open_class_depend_on_population);
                    minClassSizeContainer.expand();
                    break;
            }
        } else {
            openClassConditionTv.setText("");
            minClassSizeContainer.collapse(false);
        }
        if (formModel.getStartClassDate() != null) {
            startClassDateTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", formModel.getStartClassDate()));
        } else {
            startClassDateTv.setText("");
        }
        if (formModel.getEndClassDate() != null) {
            endClassDateTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", formModel.getEndClassDate()));
        } else {
            endClassDateTv.setText("");
        }
        if (formModel.getMinClassSize() != null) {
            minClassSizeEt.setText(formModel.getMinClassSize());
        } else {
            minClassSizeEt.setText("");
        }
        if (formModel.getConfirmDate() != null) {
            confirmDateTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", formModel.getConfirmDate()));
        } else {
            confirmDateTv.setText("");
        }
        if (formModel.getClassLocation() != null) {
            classLocationTv.setText(formModel.getClassLocation().getProvince() + " " + formModel.getClassLocation().getCity());
        } else {
            classLocationTv.setText("");
        }
        if (!TextUtils.isEmpty(formModel.getSuitableLearnAge())) {
            suitablePeopleEt.setText(formModel.getSuitableLearnAge());
        } else {
            suitablePeopleEt.setText("");
        }
        if (!TextUtils.isEmpty(formModel.getLearnTarget())) {
            learnTargetEt.setText(formModel.getLearnTarget());
        } else {
            learnTargetEt.setText("");
        }
        if (TextUtils.isEmpty(formModel.getSuitablePeople())) {
            suitablePeopleEt.setText(formModel.getSuitablePeople());
        } else {
            suitablePeopleEt.setText("");
        }
        if (formModel.getPrice() != null) {
            priceEt.setText(formModel.getPrice());
        } else {
            priceEt.setText("");
        }

        if (formModel.getCourseNumber() != null) {
            courseNumberEt.setText(formModel.getCourseNumber());
        } else {
            courseNumberEt.setText("");
        }
        if (formModel.getSingleClassDuration() != null) {
            singleClassDurationEt.setText(formModel.getSingleClassDuration());
        } else {
            singleClassDurationEt.setText("");
        }
        if (formModel.getPlatformDividend() != null) {
            platformDividendEt.setText(formModel.getPlatformDividend());
        } else {
            platformDividendEt.setText("");
        }
        formTraingCardAdapter.setNewData(formModel.getTraingCardList());
        if (ListUtil.isEmpty(formModel.getTraingCardList())) {
            traingCardTv.setVisibility(View.VISIBLE);
        } else {
            traingCardTv.setVisibility(View.INVISIBLE);
        }
        singleClassPriceEt.setText(formModel.getSinglePrice());
        boolean havePrepaidCard = false;
        for (TraingCard traingCard : formModel.getTraingCardList()) {
            if (traingCard.getType() == TraingCard.TYPE_PREPAID_CARD) {
                havePrepaidCard = true;
                break;
            }
        }
        if (havePrepaidCard) {
            singleClassPriceContainer.expand();
        } else {
            singleClassPriceContainer.collapse();
        }
        if (formModel.getStartClassDate() == null) {
            disableDateSelect();
        } else {
            enableDateSelect();
        }
        guaranteeTv.setText(GuaranteeUtil.joinGuaranteeTitle(formModel.getGuaranteeItemList(), ","));
    }

    boolean checkFormValidate() {
        boolean result = true;
        if (TextUtils.isEmpty(formModel.getTitle())) {
            result = false;
            formTitleLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            formTitleLayout.setBackgroundResource(R.color.white);
        }
        if (TextUtils.isEmpty(formModel.getMajorCourseType().getId())) {
            result = false;
            majorCourseTypeLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            majorCourseTypeLayout.setBackgroundResource(R.color.white);
        }
        if (ListUtil.isEmpty(formModel.getInterestList())) {
            result = false;
            interestLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            interestLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getClassSize())) {
            result = false;
            classSizeLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            classSizeLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getOpenClassCondition() == null) {
            result = false;
            openClassConditionLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            openClassConditionLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getOpenClassCondition() != null && formModel.getOpenClassCondition() == MajorCourseFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_POPULATION) {
            if (TextUtils.isEmpty(formModel.getMinClassSize())) {
                result = false;
                minClassSizeLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
            } else {
                minClassSizeLayout.setBackgroundResource(R.color.white);
            }

            if (formModel.getConfirmDate() == null) {
                result = false;
                confirmDateLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
            } else {
                confirmDateLayout.setBackgroundResource(R.color.white);
            }
        }

        if (formModel.getStartClassDate() == null) {
            result = false;
            startClassDateLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            startClassDateLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getEndClassDate() == null) {
            result = false;
            endClassDateLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            endClassDateLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getClassLocation() == null) {
            result = false;
            classLocationLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            classLocationLayout.setBackgroundResource(R.color.white);
        }


        if (formModel.getCover() == null) {
            result = false;
            bannerLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            bannerLayout.setBackgroundResource(R.color.white);
        }


//        if (ListUtil.isEmpty(formModel.getSuitableLearnAgeItemList())) {
//            result = false;
//            suitableLearnAgeLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
//        } else {
//            suitableLearnAgeLayout.setBackgroundResource(R.color.white);
//        }

//        if (ListUtil.isEmpty(formModel.getSelectLearnTargetItemList())) {
//            result = false;
//            learnTargetLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
//        } else {
//            learnTargetLayout.setBackgroundResource(R.color.white);
//        }

//        if (TextUtils.isEmpty(formModel.getSelectSuitablePeopleItem().getId())) {
//            result = false;
//            suitableLearnPeopleLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
//        } else {
//            suitableLearnPeopleLayout.setBackgroundResource(R.color.white);
//        }

        if (TextUtils.isEmpty(formModel.getPrice())) {
            result = false;
            priceLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            priceLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getPlatformDividend())) {
            result = false;
            platformDividendLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            platformDividendLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getCourseNumber())) {
            result = false;
            courseNumberLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            courseNumberLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getSingleClassDuration())) {
            result = false;
            singleClassDurationLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            singleClassDurationLayout.setBackgroundResource(R.color.white);
        }

//        boolean havePrepaidCard = false;
//        for (TraingCard traingCard : formModel.getTraingCardList()) {
//            if (traingCard.getType() == TraingCard.TYPE_PREPAID_CARD) {
//                havePrepaidCard = true;
//                break;
//            }
//        }
//        if (havePrepaidCard) {
//            if (TextUtils.isEmpty(formModel.getSinglePrice())) {
//                result = false;
//                singleClassPriceLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
//            } else {
//                singleClassPriceLayout.setBackgroundResource(R.color.white);
//            }
//        }
        if (!result) {
            ToastX.show(R.string.unfinish_form);
        }
        return result;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            switch (requestCode) {
                case REQUEST_CODE_EDIT_BANNER:
                    if (resultCode == RESULT_OK) {
                        ArrayList<CourseCover> resultData = data.getParcelableArrayListExtra(EditBannerPage.EXTRA_KEY_BANNER_DATA);
                        formModel.getCourseDescriptionModel().setCourseCoverList(new LinkedList<CourseCover>());
                        if (!ListUtil.isEmpty(resultData)) {
                            formModel.getCourseDescriptionModel().getCourseCoverList().addAll(resultData);
                        }
                        formModel.setCover(getDefaultCourseCover());
                    }
                    break;
                case REQUEST_CODE_INPUT_COURSE_SCHEDULE: {
                    if (resultCode == RESULT_OK) {
                        CourseScheduleModel courseScheduleModel = data.getParcelableExtra(CourseSchedulePage.EXTRA_KEY_COURSE_SCHEDULE_DATA);
                        formModel.setCourseScheduleModel(courseScheduleModel);
                    }
                    break;
                }

                case REQUEST_CODE_SELECT_CLASS_LOCATION: {
                    if (resultCode == RESULT_OK) {
                        SelectLocationData selectLocationData = data.getParcelableExtra(SelectLocationPage.EXTRA_KEY_SELECT_LOCATION);
                        formModel.setClassLocation(ClassLocation.newBuilder()
                                .city(selectLocationData.getCity())
                                .province(selectLocationData.getProvince())
                                .id(selectLocationData.getCityId())
                                .build());
                    }
                    break;
                }
                case REQUEST_CODE_SELECT_INTEREST: {
                    if (resultCode == RESULT_OK) {
                        List<Interest> interestList = data.getParcelableArrayListExtra(SelectPublishInterestPage.ACTION_INTEREST_DATA);
                        List<Interest> industryList = data.getParcelableArrayListExtra(SelectPublishInterestPage.ACTION_INDUSTRY_DATA);
                        formModel.setInterestList(interestList);
                        formModel.setIndustryList(industryList);
                    }
                    break;
                }

                case REQUEST_CODE_SELECT_TRAING_CARD: {
                    if (resultCode == RESULT_OK) {
                        List<TraingCard> traingCardList = data.getParcelableArrayListExtra(SelectTraingCardPage.EXTRA_KEY_SELECT_TRAING_CARD_DATA);
                        formModel.setTraingCardList(traingCardList);
                    }
                    break;
                }
                case REQUEST_CODE_NEXT: {
                    if (resultCode == RESULT_OK) {
                        setResult(RESULT_OK, data);
                        finish();
                    } else if (resultCode == RESULT_CANCELED) {
                        MajorCourseFormModel tempFormModel = data.getParcelableExtra(CourseDescriptionPage.EXTRA_KEY_FORM_MODEL);
                        if (tempFormModel != null) {
                            formModel = tempFormModel;
                        }
                    }
                    break;
                }


                case REQUEST_CODE_SELECT_GUARANTEE: {
                    if (resultCode == RESULT_OK) {
                        List<GuaranteeItem> selectedList = data.getParcelableArrayListExtra(GuaranteePage.EXTRA_KEY_GUARANTEE_DATA);
                        List<GuaranteeItem> guaranteeItemList = new LinkedList<>();
                        if (!ListUtil.isEmpty(selectedList)) {
                            guaranteeItemList.addAll(selectedList);
                        }
                        formModel.setGuaranteeItemList(guaranteeItemList);
                        break;
                    }
                }


                default: {
                    super.onActivityResult(requestCode, resultCode, data);
                    break;
                }
            }
        } catch (Exception e) {
        }
        updateView();
    }

    @Override
    public void onBackPressed() {
        CancelEditDialogUtil.newbuilder(this)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        EventBus.getDefault().post(EventEditMajorCourseFinish.newBuilder()
                                .resultCode(EventEditMajorCourseFinish.RESULT_CANCEL)
                                .build());
                        EventBus.getDefault().post(EventCopyMajorCourseFinish.newBuilder()
                                .resultCode(EventCopyMajorCourseFinish.RESULT_CANCEL)
                                .build());
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }

    @Override
    protected void onPause() {
        containerLayout.requestFocus();
        super.onPause();
    }

    public class RequestMajorCourseTypeAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(PublishMajorCourseFormPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().getSetup(SetupUtil.GROUP_TYPE_MAJOR_COURSE_TYPE, BuildConfig.appVersion, "all").execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<Setup> setupList = JSON.parseArray(json, Setup.class);
                majorCourseTypeList = new LinkedList<>();
                for (Setup setup : setupList) {
                    majorCourseTypeList.add(MajorCourseType.newBuilder()
                            .id(setup.getId())
                            .title((String) setup.getData().get("name"))
                            .build());
                }
                if (ListUtil.isEmpty(majorCourseTypeList)) {
                    throw new Exception(StringUtils.getString(R.string.no_result));
                }
                return null;
            } catch (Exception e) {
                majorCourseTypeList = null;
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                majorCourseTypeDialog.setData(majorCourseTypeList);
                majorCourseTypeDialog.show(getSupportFragmentManager(), "");
            }
        }
    }

    @OnClick({R.id.bannerLayout, R.id.guaranteeExplainBtn, R.id.guaranteeLayout, R.id.cspExplainBtn, R.id.platformDividendExplainBtn, R.id.majorCourseTypeLayout, R.id.confirmDateTipIv, R.id.platformDividendLayout, R.id.courseScheduleLayout, R.id.titleBackBtn, R.id.interestLayout, R.id.openClassConditionLayout, R.id.startClassDateLayout, R.id.endClassDateLayout, R.id.confirmDateLayout, R.id.classLocationLayout, R.id.traingCardLayout, R.id.nextBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bannerLayout:
                List<CourseCover> courseCoverList = new LinkedList<>();
                if (!ListUtil.isEmpty(formModel.getCourseDescriptionModel().getCourseCoverList())) {
                    courseCoverList.addAll(formModel.getCourseDescriptionModel().getCourseCoverList());
                }
                ARouter.getInstance()
                        .build(ARouterConfig.EditBannerPage)
                        .withObject("preSelectArray", courseCoverList)
                        .navigation(this, REQUEST_CODE_EDIT_BANNER);
                break;
            case R.id.guaranteeExplainBtn:
                CommonTipDialog.newInstance(StringUtils.getString(R.string.guarantee_description))
                        .show(getSupportFragmentManager(), "");
                break;
            case R.id.cspExplainBtn:
                ARouter.getInstance()
                        .build(ARouterConfig.WebViewPage)
                        .withString("url", BuildConfig.cspDescriptionUrl)
                        .navigation();
                break;
            case R.id.platformDividendExplainBtn:
                CommonTipDialog.newInstance(StringUtils.getString(R.string.platform_dividend_description))
                        .show(getSupportFragmentManager(), "");
                break;
            case R.id.majorCourseTypeLayout:
                if (majorCourseTypeList == null) {
                    new RequestMajorCourseTypeAsyncTask().execute();
                } else {
                    majorCourseTypeDialog.show(getSupportFragmentManager(), "");
                }
                break;

            case R.id.confirmDateTipIv:
                if (TextUtils.isEmpty(formModel.getMinClassSize())) {
                    CommonTipDialog.newInstance(StringUtils.getString(R.string.confirm_date_tip))
                            .show(getSupportFragmentManager(), "");
                } else {
                    CommonTipDialog.newInstance(String.format(StringUtils.getString(R.string.confirm_date_tip_template), formModel.getMinClassSize()))
                            .show(getSupportFragmentManager(), "");
                }
                break;
            case R.id.courseScheduleLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.CourseSchedulePage)
                        .withParcelable("courseScheduleModel", formModel.getCourseScheduleModel())
                        .navigation(this, REQUEST_CODE_INPUT_COURSE_SCHEDULE);
                containerLayout.requestFocus();
                break;

            case R.id.titleBackBtn:
                CancelEditDialogUtil.newbuilder(this)
                        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                                EventBus.getDefault().post(EventEditMajorCourseFinish.newBuilder()
                                        .resultCode(EventEditMajorCourseFinish.RESULT_CANCEL)
                                        .build());
                                EventBus.getDefault().post(EventCopyMajorCourseFinish.newBuilder()
                                        .resultCode(EventCopyMajorCourseFinish.RESULT_CANCEL)
                                        .build());
                            }
                        })
                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create()
                        .show();
                break;
            case R.id.interestLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.SelectPublishInterestPage)
                        .withObject("selectedInterestList", formModel.getInterestList())
                        .withObject("publishIndustryList", formModel.getIndustryList())
                        .navigation(this, REQUEST_CODE_SELECT_INTEREST);
                containerLayout.requestFocus();
                break;
            case R.id.openClassConditionLayout:
                openClassConditionDialog.show(getSupportFragmentManager(), "");
                containerLayout.requestFocus();
                break;
            case R.id.startClassDateLayout: {
                Calendar selectedDate = Calendar.getInstance();
                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                endDate.add(Calendar.YEAR, 100);
                startDate.add(Calendar.DAY_OF_YEAR, 5);
                if (formModel.getStartClassDate() != null) {
                    selectedDate.setTimeInMillis(formModel.getStartClassDate());
                } else {
                    selectedDate.setTimeInMillis(startDate.getTimeInMillis());
                }

                //时间选择器
                TimePickerView pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        if (formModel.getStartClassDate() == null || formModel.getStartClassDate() != date.getTime()) {
                            formModel.setStartClassDate(date.getTime());
                            formModel.setEndClassDate(null);
                            formModel.setConfirmDate(null);
                            updateView();
                        }
                    }
                })
                        //年月日时分秒 的显示与否，不设置则默认全部显示
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setSubmitText(getString(R.string.finish))
                        .setTitleBgColor(Color.WHITE)
                        .setBgColor(0xfff0f0f0)
                        .setLabel("", "", "", "", "", "")
                        .isCenterLabel(false)
                        .setDividerColor(Color.DKGRAY)
                        .setContentSize(21)
                        .setDate(selectedDate)
                        .setSubmitColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setCancelColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setRangDate(startDate, endDate)
                        .isDialog(true)
                        .build();
                pickerView.show();
                containerLayout.requestFocus();
                break;
            }
            case R.id.endClassDateLayout: {
                Calendar selectedDate = Calendar.getInstance();
                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                startDate.setTimeInMillis(formModel.getStartClassDate());
                endDate.setTimeInMillis(startDate.getTimeInMillis());
                endDate.add(Calendar.YEAR, 50);
                if (formModel.getEndClassDate() != null) {
                    selectedDate.setTimeInMillis(formModel.getEndClassDate());
                } else {
                    selectedDate.setTimeInMillis(startDate.getTimeInMillis());
                }
                //时间选择器
                TimePickerView pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        formModel.setEndClassDate(date.getTime());
                        updateView();
                    }
                })
                        //年月日时分秒 的显示与否，不设置则默认全部显示
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setSubmitText(getString(R.string.finish))
                        .setTitleBgColor(Color.WHITE)
                        .setBgColor(0xfff0f0f0)
                        .setLabel("", "", "", "", "", "")
                        .isCenterLabel(false)
                        .setDividerColor(Color.DKGRAY).setSubmitColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setCancelColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setContentSize(21)
                        .setDate(selectedDate)
                        .setRangDate(startDate, endDate)
                        .isDialog(true)
                        .build();
                pickerView.show();
                containerLayout.requestFocus();
                break;
            }
            case R.id.confirmDateLayout: {
                Calendar selectedDate = Calendar.getInstance();
                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                endDate.setTimeInMillis(formModel.getStartClassDate());
                endDate.add(Calendar.DAY_OF_YEAR, -1);
                startDate.add(Calendar.DAY_OF_YEAR, 1);
                if (startDate.after(endDate)) {
                    startDate.setTimeInMillis(endDate.getTimeInMillis());
                }
                if (formModel.getConfirmDate() != null) {
                    selectedDate.setTimeInMillis(formModel.getConfirmDate());
                } else {
                    selectedDate.setTimeInMillis(endDate.getTimeInMillis());
                }

                //时间选择器
                TimePickerView pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        formModel.setConfirmDate(date.getTime());
                        updateView();
                    }
                })
                        //年月日时分秒 的显示与否，不设置则默认全部显示
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setSubmitText(getString(R.string.finish))
                        .setTitleBgColor(Color.WHITE)
                        .setBgColor(0xfff0f0f0)
                        .setLabel("", "", "", "", "", "")
                        .isCenterLabel(false)
                        .setDividerColor(Color.DKGRAY).setSubmitColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setCancelColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setContentSize(21)
                        .setDate(selectedDate)
                        .setRangDate(startDate, endDate)
                        .isDialog(true)
                        .build();
                pickerView.show();
                containerLayout.requestFocus();
                break;
            }
            case R.id.classLocationLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.SelectLocationPage)
                        .navigation(this, REQUEST_CODE_SELECT_CLASS_LOCATION);
                containerLayout.requestFocus();
                break;
            case R.id.suitableLearnAgeLayout:
                break;
            case R.id.learnTargetLayout:
                break;
            case R.id.suitableLearnPeopleLayout:
                break;
            case R.id.tagLayout:
                break;
            case R.id.traingCardLayout: {
                ARouter.getInstance()
                        .build(ARouterConfig.SelectTraingCardPage)
                        .withObject("selectedCards", formModel.getTraingCardList())
                        .navigation(this, REQUEST_CODE_SELECT_TRAING_CARD);
                containerLayout.requestFocus();
                break;
            }
            case R.id.guaranteeLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.GuaranteePage)
                        .withObject("preSelectArray", formModel.getGuaranteeItemList())
                        .navigation(this, REQUEST_CODE_SELECT_GUARANTEE);
                break;
            case R.id.nextBtn:
                if (keyboardVisiable) {
                    KeyboardUtil.hideKeyboard(this, containerLayout);
                    confirmDateLayout.requestFocus();
                    return;
                }

                if (checkFormValidate()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.CourseDescriptionPage)
                            .withParcelable("majorCourseFormModel", formModel)
                            .navigation(this, REQUEST_CODE_NEXT);
                }
                break;
        }
    }

    public void disableDateSelect() {
        if (formModel.getSellCount() > 0) return;
        UIHelper.setViewAndChildrenEnabled(endClassDateLayout, false);
        UIHelper.setViewAndChildrenEnabled(confirmDateLayout, false);
        confirmDateTipIv.setEnabled(true);
    }

    public void maybeFreezeForm() {
        if (formModel.getSellCount() <= 0) return;
        UIHelper.setViewAndChildrenEnabled(classSizeLayout, false);
        UIHelper.setViewAndChildrenEnabled(openClassConditionLayout, false);
        UIHelper.setViewAndChildrenEnabled(startClassDateLayout, false);
        UIHelper.setViewAndChildrenEnabled(endClassDateLayout, false);
        UIHelper.setViewAndChildrenEnabled(minClassSizeContainer, false);
        UIHelper.setViewAndChildrenEnabled(classLocationLayout, false);
        UIHelper.setViewAndChildrenEnabled(priceLayout, false);
        UIHelper.setViewAndChildrenEnabled(singleClassDurationLayout, false);
        UIHelper.setViewAndChildrenEnabled(platformDividendLayout, false);
        UIHelper.setViewAndChildrenEnabled(cspLayout, false);
        confirmDateTipIv.setEnabled(true);
        platformDividendExplainBtn.setEnabled(true);
        cspExplainBtn.setEnabled(true);
    }

    public void enableDateSelect() {
        if (formModel.getSellCount() > 0) return;
        UIHelper.setViewAndChildrenEnabled(endClassDateLayout, true);
        UIHelper.setViewAndChildrenEnabled(confirmDateLayout, true);
    }

    public class DependOnPopulationNotifyTask extends SafeAsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog = null;

        public DependOnPopulationNotifyTask(Activity activity) {
            super(activity);
            if (dependOnPopulationNotify == null) {
                loadingDialog = LoadingDialog.newBuilder()
                        .with(PublishMajorCourseFormPage.this)
                        .message(R.string.loading)
                        .show();
            }
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
            if (o instanceof Exception) {

            } else {
                CommonTipDialog.newInstance(dependOnPopulationNotify)
                        .show(getSupportFragmentManager(), "");
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            if (dependOnPopulationNotify != null) return null;
            try {
                Response<ResponseBody> response = ApiManager.getService().getDependOnPopulationNotify().execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                JSONArray jsonArray = JSON.parseArray(json);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                JSONObject data = JSON.parseObject(jsonObject.getString("data"));
                dependOnPopulationNotify = data.getString("desc");
                if (dependOnPopulationNotify == null) {
                    throw new Exception(StringUtils.getString(R.string.unknown_error));
                }
                return null;
            } catch (Exception e) {
                dependOnPopulationNotify = null;
                return e;
            }
        }
    }

    public class MaybeRequestDivide extends SafeAsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        boolean shouldRequest;
        MajorCourseFormModel model;

        public MaybeRequestDivide(Activity activity, MajorCourseFormModel model) {
            super(activity);
            this.model = model;
            divide = DivideUtil.getMajorCourseDivide();
            shouldRequest = divide == null;
            if (shouldRequest) {
                loadingDialog = LoadingDialog.newBuilder()
                        .with(activity)
                        .message(R.string.loading)
                        .build();
            } else {
                loadingDialog = null;
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (loadingDialog != null) {
                loadingDialog.showLoading();
            }
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
            if (TextUtils.isEmpty(model.getPlatformDividend())) {
                model.setPlatformDividend(StringUtils.platformDividendFormat(divide.getDefaultValue() * 100));
            }
            updateView();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            if (!shouldRequest) {
                return null;
            }
            try {
                Response<ResponseBody> response = ApiManager.getService().getMajorCourseDivide().execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                JSONArray jsonArray = JSON.parseArray(json);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                JSONObject data = JSON.parseObject(jsonObject.getString("data"));
                double max = data.getDouble("max");
                double min = data.getDouble("min");
                double defaultValue = data.getDouble("default");
                divide = Divide.newBuilder()
                        .defaultValue(defaultValue)
                        .max(max)
                        .min(min)
                        .timestamp(System.currentTimeMillis())
                        .build();
                DivideUtil.putMajorCourseDivide(divide);
            } catch (Exception e) {
                divide = Divide.newBuilder()
                        .defaultValue(0.3)
                        .max(1)
                        .min(0.03)
                        .timestamp(0)
                        .build();
            }
            return null;
        }
    }

}
